package lion.web.interceptors.ipac;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import lion.dev.matcher.FullMatcher;
import lion.dev.matcher.Matcher;
import lion.dev.matcher.PrefixMatcher;
import lion.dev.matcher.RegexMatcher;
import lion.dev.matcher.WildCardMatch;
import lion.framework.core.web.path.PathVar;

/**
 * @author lion
 * @email hl_0074@sina.com
 * @date 2014年5月8日
 */
public class IPAC {

	private String path;
	private List<Matcher> ipMatchers = new ArrayList<>();
	private Matcher pathMatcher;

	public IPAC(String path, String ipPattern) {

		this.path = path;
		path = PathVar.replacePathVars(path);
		if (this.path.indexOf("*") > -1) {
			this.pathMatcher = new WildCardMatch(path);
		} else {
			this.pathMatcher = new PrefixMatcher(path);
		}

		String[] ips = StringUtils.split(ipPattern, ",");

		for (String ip : ips) {
			if (ip.indexOf("*") > -1) {
				ipMatchers.add(new WildCardMatch(ip));
			} else if (ip.indexOf("[") > -1) {
				ipMatchers.add(new RegexMatcher(ip));
			} else {
				ipMatchers.add(new FullMatcher(ip));
			}
		}
	}

	public boolean access(String ip) {

		for (Matcher matcher : this.ipMatchers) {
			if (matcher.match(ip)) { return true; }

		}
		return false;
	}

	public boolean match(String path) {

		return this.pathMatcher.match(path);
	}
}
